﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Radio;
using DG.Tweening;

public class DiantaiPlay : MonoBehaviour
{
    protected Button btn_back;
    protected Button btn_share;
    protected Text text_title;
    protected Image img_bg_blur_mat;
    protected Image img_bg_blur;
    protected Image img_bg;
    protected Text text_time_progress;
    protected Text text_time_all;
    protected Button btn_pre;
    protected Button btn_next;
    protected Toggle toggle_play_pause;

    protected Slider slider_music;
    protected RectTransform rect_slider;

    protected GameObject _loadingCircle;
    protected DOTweenAnimation dotweenAnimation;
    #region dataCache
    protected string json;
    protected int currentIndex = 0;
    protected int lastIndex = 0;
    protected List<RadioJsonData> jsonList;
    protected List<RadioViewItem> itemlist;

    protected int updateInterval = 10;//每几帧更新一次数据
    protected int timer = 0;

    protected float currentAudioLength = 0;
    protected float currentplayedLength = 0;

    protected Vector2 sliderMinMax;

    protected RadioPlayerState lastState;
    #endregion

    #region switch
    protected bool hasInitialized = false;
    protected bool playerInitialized = false;
    protected bool isPlay = false;

    protected bool isDragging = false;
    #endregion

    protected Camera m_camera
    {
        get
        {
            return transform.parent.GetComponent<HUIFormScript>().GetCamera();
        }
    }

    private void OnEnable()
    {
        if (!hasInitialized) _initilatize();
        _register();
        _updateInfo();
        _play(0);

        btn_back.enabled = false;

        Invoke("UnLockReturnBtn", 2f);
    }

    private void OnDisable()
    {
        _unRegister();
        DataClear();
        ComponentReset();
        //RadioSDKManager.Instance.Destroy();
        Play(false);
        

        YOUMENG_END();
    }

    void UnLockReturnBtn()
    {
        btn_back.enabled = true;
    }

    protected void _initilatize()
    {
        btn_back = transform.Find("btn_return").GetComponent<Button>();
        btn_share = transform.Find("btn_share").GetComponent<Button>();
        text_title = transform.Find("title_text").GetComponent<Text>();
        img_bg_blur = transform.Find("blur_content/background").GetComponent<Image>();
        img_bg_blur_mat = transform.Find("blur_content/blur").GetComponent<Image>();
        dotweenAnimation = transform.Find("circle_mask").GetComponent<DOTweenAnimation>();
        img_bg = transform.Find("circle_mask/Image").GetComponent<Image>();
        text_time_progress = transform.Find("progress_slider/played_text").GetComponent<Text>();
        text_time_all = transform.Find("progress_slider/all_text").GetComponent<Text>();
        btn_pre = transform.Find("btn_pre").GetComponent<Button>();
        btn_next = transform.Find("btn_next").GetComponent<Button>();
        toggle_play_pause = transform.Find("play_btn").GetComponent<Toggle>();

        slider_music = transform.Find("progress_slider").GetComponent<Slider>();
        rect_slider = slider_music.transform as RectTransform;

        _loadingCircle = slider_music.handleRect.transform.GetChild(0).gameObject;

        bool showShare = SDKManager.Instance.isRainbowFMShare();
        btn_share.gameObject.SetActive(showShare);

        lastState = RadioPlayerState.none;
        hasInitialized = true;
    }

    protected void Share()
    {
        Debug.Log("share");
        //toggle_play_pause.isOn = false;
        //Play(false);//pause
        //ScreenCapture.CaptureScreenshot(RadioDataPool.screenShotFile);
        //SDKManager.Instance.ShareImage(RadioDataPool.screenShotFile);
        RadioJsonData ji = jsonList[currentIndex % jsonList.Count];
        string imgUrl = ji.audioBgUrl;
        SDKManager.Instance.ShareImage(ji.audioBgUrl);

    }

    protected void Pre()
    {
        Debug.Log("pre");
        currentIndex--;
        currentIndex = (currentIndex + jsonList.Count) % jsonList.Count;
        _play(0);
    }

    protected void Next()
    {
        Debug.Log("next");
        currentIndex++;
        currentIndex = (currentIndex + jsonList.Count) % jsonList.Count;
        _play(0);
        _updateInfo();
        ComponentReset();
    }

    private int timerSeq;
    private const float adsTime = 10;
    protected void Play(bool isOn)
    {
        Debug.Log(isOn ? "Play" : "Pause");
        if (isOn)
        {
            _updateInfo();
            YOUMENG_BEGIN();
            RadioSDKManager.Instance.Play(currentIndex % jsonList.Count, Mathf.CeilToInt(currentplayedLength));
            dotweenAnimation.DOPlay();
            lastState = RadioPlayerState.play;
            //Debug.Log("<color=green>..播放..</color>");

            InputTimerManager.Instance.RemoveTimer(timerSeq);
            timerSeq = InputTimerManager.Instance.AddTimer(adsTime, false, ShowAds);
        }
        else
        {
            RadioSDKManager.Instance.Pause();
            dotweenAnimation.DOPause();
            lastState = RadioPlayerState.pause;
            InputTimerManager.Instance.RemoveTimer(timerSeq);
        }
    }

    private void ShowAds(int seq)
    {
        if (lastState == RadioPlayerState.pause)
        {
            return;
        }
        AdsManager.Instance.ShowAds(AdsNameConst.Ads_Diantai);
    }

    protected void _register()
    {
        btn_share.onClick.AddListener(Share);
        btn_pre.onClick.AddListener(Pre);
        btn_next.onClick.AddListener(Next);
        toggle_play_pause.onValueChanged.AddListener(Play);

        HUIEventManager.Instance.AddUIEventListener(enUIEventID.Radio_Slider_DragBegin, SliderDragBegin);
        HUIEventManager.Instance.AddUIEventListener(enUIEventID.Radio_Slider_DragEnd, SliderDragEnd);
        HUIEventManager.Instance.AddUIEventListener(enUIEventID.Radio_Slider_Click, SliderDragClick);
    }

    protected void _unRegister()
    {
        btn_share.onClick.RemoveListener(Share);
        btn_pre.onClick.RemoveListener(Pre);
        btn_next.onClick.RemoveListener(Next);
        toggle_play_pause.onValueChanged.RemoveListener(Play);

        HUIEventManager.Instance.RemoveUIEventListener(enUIEventID.Radio_Slider_DragBegin, SliderDragBegin);
        HUIEventManager.Instance.RemoveUIEventListener(enUIEventID.Radio_Slider_DragEnd, SliderDragEnd);
        HUIEventManager.Instance.RemoveUIEventListener(enUIEventID.Radio_Slider_Click, SliderDragClick);
    }

    protected void SliderDragBegin(HUIEvent hUIEvent)
    {
        isDragging = true;
    }

    protected void SliderDragEnd(HUIEvent hUIEvent)
    {
        isDragging = false;

        float v = slider_music.value;

        _play(currentAudioLength * v);
    }

    protected void SliderDragClick(HUIEvent hUIEvent)
    {
        Vector2 pointerPosition = new Vector2(hUIEvent.m_eventParams.argFloat, hUIEvent.m_eventParams.argFloat2);
        Vector2 Offset;
        if (RectTransformUtility.ScreenPointToLocalPointInRectangle(slider_music.handleRect, pointerPosition, m_camera, out Offset))
        {
            float w = rect_slider.rect.width;
            float nowpin = w * slider_music.value;
            float clickpin = nowpin + Offset.x;

            float v = clickpin / w;
            slider_music.value = v;

            _play(currentAudioLength * v);
            //Debug.Log(v);
        }
    }

    protected void _play(float time)
    {
        currentplayedLength = time;
        toggle_play_pause.isOn = true;
        toggle_play_pause.onValueChanged.Invoke(true);
    }

    protected void ComponentReset()
    {
        slider_music.value = 0f;
    }

    protected void DataClear()
    {
        json = string.Empty;
        currentIndex = 0;
        currentAudioLength = 300;
        currentplayedLength = 0f;
        isPlay = false;
        playerInitialized = false;
        toggle_play_pause.isOn = false;
    }

    /// <summary>
    /// 注入灵魂
    /// </summary>
    /// <param name="json">播放曲目的所有信息</param>
    /// <param name="yourClickedItemIndex">你的曲目在所有曲目中的位置</param>
    public void InjectData(string json, int yourClickedItemIndex, List<RadioViewItem> itemlist)
    {
        this.json = json;
        this.itemlist = itemlist;
        currentIndex = yourClickedItemIndex;
        jsonList = JsonUtility.FromJson<JsonSerialization<RadioJsonData>>(json).ToList();


        string j = json;
        j = j.Replace("{\"Data\":[", "[");
        j = j.Replace("]}", "]");

        //Debug.Log(j);
#if UNITY_EDITOR
        RadioSDKManager.Instance.InitRadio(json);
        Debug.Log(json);
#else

        RadioSDKManager.Instance.InitRadio(j);
        
#endif
        playerInitialized = true;
    }

    protected void _updateInfo()
    {
        RadioJsonData ji = jsonList[currentIndex % jsonList.Count];
        text_title.text = ji.audioMainTitle;
        //Debug.Log(ji.audioBgUrl+"   "+ji.audioMainTitle + "   "+ji.audioSubTitle);
        RadioUIHelper.SetImg(img_bg, ji.audioBgUrl, RadioDataPool.imgRect);
        RadioUIHelper.SetImg(img_bg_blur, ji.audioBgUrl, RadioDataPool.imgRect);
        RadioUIHelper.SetImg(img_bg_blur_mat, ji.audioBgUrl, RadioDataPool.imgRect);
        img_bg_blur_mat.material.mainTexture = RadioDataPool.Instance.textures[FileTools.GetMD5FromString(ji.audioBgUrl)];

        bool showShare = SDKManager.Instance.isRainbowFMShare();
        string imgUrl = ji.audioBgUrl;
        btn_share.gameObject.SetActive(showShare && FileTools.IsFileExist(imgUrl));

    }

    protected void YOUMENG_BEGIN()
    {
        RadioViewItem data = itemlist[currentIndex % itemlist.Count];
        UmengLevel level = (UmengLevel)data.leadershipTag;

        SDKManager.Instance.StartLevel(level);
    }

    protected void YOUMENG_END()
    {
        RadioViewItem data = itemlist[currentIndex % itemlist.Count];
        UmengLevel level = (UmengLevel)data.leadershipTag;

        SDKManager.Instance.FinishLevel(level);
    }

    protected bool IsEnterHoldTiming = false;
    protected float holdTimer = 0f;
    private void Update()
    {
        if (!playerInitialized) return;
        timer++;
        if (timer % updateInterval == 0)
        {
            timer = 0;

            if (RadioSDKManager.Instance.IsPlaying()/* && !IsEnterHoldTiming*/)
            {
                _updateProgress();
                //IsEnterHoldTiming = IsJumpNext();
            }
            return;
            if (IsEnterHoldTiming && lastState == RadioPlayerState.play)
            {
                holdTimer += updateInterval * Time.deltaTime;
                slider_music.value = 0.99f;
                if (holdTimer >= 1.50f)
                {
                    holdTimer = 0f;
                    IsEnterHoldTiming = false;
                    YOUMENG_END();
                    //Next();
                }
            }
        }
    }

    protected bool IsJumpNext()
    {
        string pr = RadioSDKManager.Instance.GetProgress();
        RadioJsonProgress jp = JsonUtility.FromJson<RadioJsonProgress>(pr);

        float exp = jp.curAudioPlayProgress - currentAudioLength;
        //Debug.Log(string.Format("<color=green>{0} {1} {2}</color>",exp,jp.curAudioPlayProgress,currentAudioLength));
        if (exp >= 0 || Mathf.Abs(exp) <= 1f)//这个地方会出现卡住最后一秒的情况，那么就设置一个定时器1S之后切歌
            return true;

        return false;
    }


    protected void _updateProgress()
    {
        //RadioJsonInfo ji = RadioDataPool.Instance.GetRadioInfo(currentIndex % jsonList.Count);
        string ai = RadioSDKManager.Instance.GetInfo();
        RadioJsonInfo ji = JsonUtility.FromJson<RadioJsonInfo>(ai);
        if (ji != null)
        {
            currentAudioLength = ji.audioTotalTime;


            string pr = RadioSDKManager.Instance.GetProgress();
            RadioJsonProgress jp = JsonUtility.FromJson<RadioJsonProgress>(pr);

            if (!isDragging)
                slider_music.value = jp.curAudioPlayProgress / currentAudioLength;

            text_time_all.text = RadioClassHelper.Clock(Mathf.CeilToInt(currentAudioLength));
            currentplayedLength = jp.curAudioPlayProgress;

            int loadedTime = RadioSDKManager.Instance.GetAudioLoadedTime();
            _loadingCircle.SetActive((loadedTime / Mathf.CeilToInt(currentAudioLength)) < slider_music.value);
            text_time_progress.text = RadioClassHelper.Clock(Mathf.CeilToInt(currentplayedLength));

            currentIndex = ji.audioID;
            if (currentIndex != lastIndex)
            {
                //last finish.
                RadioViewItem data = itemlist[lastIndex % itemlist.Count];
                UmengLevel level = (UmengLevel)data.leadershipTag;

                SDKManager.Instance.FinishLevel(level);

                YOUMENG_BEGIN();
                _updateInfo();
            }

            lastIndex = currentIndex;
        }
        
    }

}

//无论播放状态是什么，当缓冲值<播放值的时候，加载圆圈就会显示，否则不显示.

public enum RadioPlayerState
{
    none,
    play,
    pause,
}